package com.sgb.zhaocai.view.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.link.entity.PickInvitedApply;
import com.sgb.zhaocai.R;
import com.sgb.zhaocai.databinding.PickMemberPersonalFragmentBinding;
import com.sgb.zhaocai.entity.MemberCompanyEntitly;
import com.sgb.zhaocai.view.activity.PickInvitedApplyDetailsActivity;
import com.sgb.zhaocai.view.adapter.MemberCompanyAdapter;
import com.sgb.zhaocai.view.adapter.MemberPersonalAdapter;
import com.sgb.zhaocai.viewmodel.PickMemberCompanyModel;
import com.sgb.zhaocai.viewmodel.PickMemberPersonalModel;
import com.sgb.zhaocai.widget.MemberTypePopWindow;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * 会员单位-个人
 */
public class PickMemberPersonalFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener{

    private PickMemberPersonalFragmentBinding mBinding;
    private PickMemberPersonalModel mModel;
    private static String DATA = "data";
    private PickInvitedApply bean;
    private boolean isLoadMore = false;
    private int num = 0;
    private MemberPersonalAdapter memberpersonaladapter;
    private String SearchNames = "";
    private static String FROMWHERE = "fromWhere";
    private String fromWhere;
    private boolean isSelectAll = false;
    private String membergrade = "";
    private String memberTypeName = "";
    private MemberTypePopWindow memberTypePop;
    private String memberTypeNo = "";
    private List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>>>> memberTypeList;
    private String time = "";
    private boolean isTextView = false;

    public static PickMemberPersonalFragment newInstance(PickInvitedApply pickinvitedapply,String fromWhere) {
        PickMemberPersonalFragment fragment = new PickMemberPersonalFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(DATA, pickinvitedapply);
        bundle.putString(FROMWHERE, fromWhere);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.pick_member_personal_fragment, container, false);
        mModel = new ViewModelProvider(this).get(PickMemberPersonalModel.class);
        mModel.setActivity(PickMemberPersonalFragment.this);
        bean = (PickInvitedApply) getArguments().get(DATA);
        fromWhere =(String) getArguments().get(FROMWHERE);
        if (!TextUtils.isEmpty(bean.getMemberLevel())){
            membergrade=bean.getMemberLevel();
        }
        return mBinding.getRoot();
    }

    @Override
    protected void onLazyLoad() {

    }

    private void initData(boolean isLoadMore) {
        mModel.getMixMemberListByPage(isLoadMore,SearchNames,memberTypeNo,membergrade);
    }

    @Override
    protected void initView() {
        super.initView();
        if (memberpersonaladapter == null) {
            memberpersonaladapter = new MemberPersonalAdapter(getActivity(), null);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mBinding.recyclerView.setLayoutManager(layoutManager);
        mBinding.recyclerView.setHasFixedSize(true);
        //解决数据加载完成后, 没有停留在顶部的问题
        mBinding.recyclerView.setFocusable(false);
        mBinding.recyclerView.setAdapter(memberpersonaladapter);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                initData(isLoadMore);
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                //上拉加载更多
                initData(isLoadMore);
            }
        });
        memberpersonaladapter.onIChildClick(new MemberPersonalAdapter.IChildClick() {
            @Override
            public void onClick(MemberCompanyEntitly membercompanyentitly) {
                membercompanyentitly.setCheck(!membercompanyentitly.isCheck());
                memberpersonaladapter.notifyDataSetChanged();
                invitedSureData();
            }
        });
        //全选按钮
        mBinding.llCheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSelectAll){
                    isSelectAll = false;
                    mBinding.checkImageview.setImageResource(R.drawable.icon_ring );
                    mBinding.invitedSure.setText("确认邀请");
                    mBinding.invitedSure.setBackground(getActivity().getResources().getDrawable(R.drawable.bg_tint_orange_5));
                    isTextView = false;
                }else {
                    isSelectAll = true;
                    mBinding.checkImageview.setImageResource(R.drawable.icon_select_item );
                    mBinding.invitedSure.setText("确认邀请("+memberpersonaladapter.getDatas().size()+")");
                    mBinding.invitedSure.setBackground(getActivity().getResources().getDrawable(R.drawable.bg_orange_5));
                    isTextView = true;
                }

                for (MemberCompanyEntitly data : memberpersonaladapter.getDatas()) {
                    data.setCheck(isSelectAll);
                }
                memberpersonaladapter.notifyDataSetChanged();

            }
        });
        //确认邀请实现
        mBinding.invitedSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isTextView){
                    invitedSureDataList();
                }
            }
        });

        //置顶
        mBinding.imgBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBinding.imgBackTop.setVisibility(View.GONE);
                mBinding.recyclerView.getLayoutManager().scrollToPosition(0);
            }
        });
        viewData();
    }

    private void viewData() {
        //初始化popview
        initializePopView();
    }

    private void initializePopView() {
        //会员类型
            initMemberPopup();
        //会员等级
        mBinding.memberGrade.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mModel.getMemberGrade();
    }
    private void initMemberPopup() {
        mBinding.memberType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (memberTypeList == null || memberTypeList.size() == 0) {
                    mModel.getMemberTypeList();
                    return;
                }
                mBinding.popLine.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(memberTypeName) ) {
                    mBinding.memberType.updateChooseTextStatus(-2, null);
                } else {
                    mBinding.memberType.updateChooseTextStatus(-1, mBinding.memberType.getKeyName());
                }
                memberTypePop.showPopwindow0(mBinding.popLine);
            }
        });
        memberTypePop = new MemberTypePopWindow(getActivity());
        memberTypePop.setBgView(mBinding.grayLayout);
        memberTypePop.setCategoryCallBack(new MemberTypePopWindow.CategoryCallBack() {
            @Override
            public void resultPosition(PickSelectEntity oneName, PickSelectEntity twoName, PickSelectEntity threeName, PickSelectEntity fourName, PickSelectEntity fiveName, int onePos, int twoPos, int threePos, int fourPos, int fivePos) {
                //确定
                memberTypeName = "";
                memberTypeNo = "";
                mBinding.memberType.updateChooseTextStatus(0, mBinding.memberType.getKeyName());
                if (!TextUtils.isEmpty(oneName.getNo())) {
                    memberTypeNo = oneName.getNo();
                    memberTypeName = oneName.getProjectscale();
                }
                if (!TextUtils.isEmpty(twoName.getNo())) {
                    memberTypeNo = twoName.getNo();
                    memberTypeName = twoName.getProjectscale();
                }
                if (!TextUtils.isEmpty(threeName.getNo())) {
                    memberTypeNo = threeName.getNo();
                    memberTypeName = threeName.getProjectscale();
                }
                if (!TextUtils.isEmpty(fourName.getNo())) {
                    memberTypeNo = fourName.getNo();
                    memberTypeName = fourName.getProjectscale();
                }
                if (!TextUtils.isEmpty(fiveName.getNo())) {
                    memberTypeNo = fiveName.getNo();
                    memberTypeName = fiveName.getProjectscale();
                }
                if (TextUtils.isEmpty(memberTypeName)||memberTypeName.equals("全部")){
                    mBinding.memberType.updateChooseTextStatus(-1, "会员类型");
                }else{
                    mBinding.memberType.updateChooseTextStatus(1, memberTypeName);
                }
                //刷新数据
                initData(false);
            }

            @Override
            public void resetPosition() {

            }
        });
        memberTypePop.setOnDismissListener(() -> {
            if (!TextUtils.isEmpty(memberTypeName) ) {
                mBinding.memberType.updateChooseTextStatus(1, null);
            } else {
                mBinding.memberType.updateChooseTextStatus(0, mBinding.memberType.getKeyName());
            }
        });

    }

    public void setMemberTypeList(List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>>>> data) {
        if (data!=null&&data.size()>0){
            this.memberTypeList = data;
            memberTypePop.setData(memberTypeList);
            mBinding.popLine.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(memberTypeName) ) {
                mBinding.memberType.updateChooseTextStatus(-2, null);
            } else {
                mBinding.memberType.updateChooseTextStatus(-1, mBinding.memberType.getKeyName());
            }
            memberTypePop.showPopwindow0(mBinding.popLine);
        }
    }

    //pop初始化数据
    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "会员等级":
                mModel.getMemberGrade();
                break;
        }
    }

    //pop点击事件
    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        String name = position == 0 ? "" : entity.getTypeName();
        switch (mKeyName) {
            case "会员等级":
                if (!TextUtils.equals(no, membergrade)) {
                    if (TextUtils.isEmpty(no)){
                        if (!TextUtils.isEmpty(bean.getMemberLevel())){
                            membergrade = bean.getMemberLevel();
                        }else {
                            membergrade = "";
                        }
                    }else {
                        membergrade = no;
                    }
                }
                break;
        }
        //刷新数据
        initData(false);
    }

    public void setMemberGradeList(List<CommonPopEntity> datas) {
        List<CommonPopEntity> MemberLevelList = new ArrayList<>();
        if (!TextUtils.isEmpty(bean.getMemberLevel())){
            for (int i = 0; i < datas.size(); i++) {
                if (Integer.parseInt(datas.get(i).getNo())>=Integer.parseInt(bean.getMemberLevel())){
                    MemberLevelList.add(datas.get(i));
                }else {
                    if (TextUtils.equals(datas.get(i).getNo(),"0")){
                        datas.get(i).setNo(bean.getMemberLevel());
                        MemberLevelList.add(datas.get(i));
                    }
                }
            }
        }else {
            MemberLevelList.addAll(datas);
        }
        setChooseItemData(1, MemberLevelList);
    }

    //弹窗信息
    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        switch (type) {
            case 1://会员等级
                mBinding.memberGrade.setData(data, membergrade);
                break;
        }
    }

    public void setMixMemberListByPage(List<MemberCompanyEntitly> data, boolean isLastPage) {
        RecyclerRefreshing();
        if (isLoadMore) {
            if (data != null && data.size() > 0) {
                memberpersonaladapter.addDatas(data);
            }
            mBinding.imgBackTop.setVisibility(View.VISIBLE);
            mBinding.recyclerView.setNoMore(isLastPage);
        } else {
            if (data != null && data.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mBinding.recyclerView.setVisibility(View.VISIBLE);
                mBinding.llBottom.setVisibility(View.VISIBLE);
                memberpersonaladapter.clearDatas();
                memberpersonaladapter.setDatas(data);
                mBinding.recyclerView.scrollToPosition(0);
                mBinding.recyclerView.setNoMore(isLastPage);
                mBinding.imgBackTop.setVisibility(View.GONE);
            } else {
                memberpersonaladapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
                mBinding.recyclerView.setVisibility(View.GONE);
                mBinding.llBottom.setVisibility(View.GONE);
                mBinding.imgBackTop.setVisibility(View.GONE);
            }
        }
        invitedSureData();
    }

    private void invitedSureData() {
        num=0;
        if (memberpersonaladapter.getDatas()!=null&&memberpersonaladapter.getDatas().size()>0){
            for (MemberCompanyEntitly datas : memberpersonaladapter.getDatas()) {
                if (!datas.isCheck()){
                    //全选按钮设置成不全选
                    if (isSelectAll){
                        isSelectAll = false;
                    }
                    mBinding.checkImageview.setImageResource(R.drawable.icon_ring );
                }else {
                    num++;
                }
            }
            if (num == 0){
                mBinding.invitedSure.setText("确认邀请");
                mBinding.invitedSure.setBackground(getActivity().getResources().getDrawable(R.drawable.bg_tint_orange_5));
                isTextView = false;
            }else {
                mBinding.invitedSure.setText("确认邀请("+num+")");
                mBinding.invitedSure.setBackground(getActivity().getResources().getDrawable(R.drawable.bg_orange_5));
                isTextView = true;
            }
        }
    }


    private void RecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void initSearch(String searchName) {
        this.SearchNames = searchName;
        initData(false);
    }

    //提交数据
    private void invitedSureDataList() {
        List<String> userList = new ArrayList<>();
        List<String> userNameList = new ArrayList<>();
        if (TextUtils.equals(fromWhere, "1")) {
            time =   bean.getApplyEndTime();
        } else {
            time = "";
        }
        for (MemberCompanyEntitly data : memberpersonaladapter.getDatas()) {
            if (data.isCheck()){
                userList.add(data.getBusinessNo());
                userNameList.add(data.getName());
            }
        }
        if (userList.size()>0){
            PickInvitedApplyDetailsActivity.start(getActivity(), fromWhere, bean.getName(), time, 0, new ArrayList<>(),bean.getId(),userList,new ArrayList<>(),userNameList,0,"");
        }/*else {
            MToast.showToast(getActivity(),"请选择会员单位个人数据");
        }*/
    }

    //重置筛选项
    public void RemoveScreenData() {
        initializePopView();
        //地址清除
        if (!TextUtils.isEmpty(bean.getMemberLevel())){
            membergrade=bean.getMemberLevel();
        }else {
            membergrade = "";
        }
        memberTypeNo = "";
        memberTypeName = "";
        if (memberTypeList != null && memberTypeList.size() > 0) {
            memberTypePop.setData(memberTypeList);
        }
        mBinding.memberType.updateChooseTextStatus(0, mBinding.memberType.getKeyName());
        mBinding.memberGrade.updateChooseTextStatus(0, mBinding.memberType.getKeyName());
        initData(false);
    }
}
